<template xmlns:background-color="http://www.w3.org/1999/xhtml">
  <a-row :gutter="10">
    <a-col :md="5" :sm="24" >
      <a-card style="min-height: 80vh">
        <div>
          <slot name="left-top"></slot>
        </div>
        <div v-if="tabVal=='1'">
          <slot name="left-top-extra"></slot>
        </div>
        <div v-if="tabVal=='2'">
          <slot name="left-top-line-extra"></slot>
        </div>
        <a-tabs @change="changeTabs" :value="tabVal">
        <a-tab-pane tab="单元分区" key="1" v-if="!onlyShowLine">
          <div style="margin-bottom: 12px;padding:0 16px">
            <slot name="left-top-inner"></slot>
          </div>
          <div style="background: #fff;padding:0 16px;height: 100%; margin-top: 5px">
            <a-alert type="info" :showIcon="true">
              <div slot="message">
                当前选择：<span v-if="this.currSelected.title">{{ getCurrSelectedTitle() }}</span>
                <a v-if="this.currSelected.title" style="margin-left: 10px" @click="onClearSelected">取消选择</a>
              </div>
            </a-alert>
            <a-input-search @search="onSearch" style="width:100%;margin-top: 10px" placeholder="请输入分区名称"/>
            <!-- 树-->
            <a-col :md="10" :sm="24" style="height:60vh;overflow-y: auto;width: 100%">
              <div>
                <a-dropdown :trigger="[this.dropTrigger]" @visibleChange="dropStatus">
                <span style="user-select: none">
                  <a-tree
                    key="tree"
                    :checkable="cancheckable==null?true:false"
                    multiple
                    @select="onSelect"
                    @check="onCheck"
                    :selectedKeys="selectedKeys"
                    :checkedKeys="checkedKeys"
                    :treeData="departTree"
                    :checkStrictly="checkStrictly"
                    :expandedKeys="iExpandedKeys"
                    :autoExpandParent="autoExpandParent"
                    @expand="onExpand"/>
                </span>
                </a-dropdown>
              </div>
            </a-col>
          </div>
        </a-tab-pane>
        <a-tab-pane tab="分项系统" key="2" v-if="showLine||onlyShowLine">
          <div style="margin-bottom: 12px;padding:0 16px">
            <slot name="left-top-line-inner"></slot>
          </div>
          <div style="height:60vh;overflow-y: auto;margin-top:5px;padding:0 16px">
            <a-alert type="info" :showIcon="true">
              <div slot="message">
                当前选择：<span v-if="this.item.id">{{ this.item.systemName }}</span>
                <a v-if="this.item.id" style="margin-left: 10px" @click="onClearLineSelected">取消选择</a>
              </div>
            </a-alert>
            <a-input-search v-model="lineText" @search="onSearchLine" style="width:100%;margin-top: 10px" placeholder="请输入分项系统名称"/>
            <div :tabIndex="index" v-for="(item, index) in itemList"  style="position: relative;margin-top:5px">
              <input @click="handleDetail(item,index)" type="radio" class="faux" :value="item" :checked="iIndex==index"
                     name="inst" />
              <div class="inst-item">

                <div v-if="item.status"><img src="~@/assets/eneMon/green.svg" alt="">&nbsp{{
                    item.systemName }}</div>
                <div v-else><img style="filter: grayscale(100%)"
                                                         src="~@/assets/eneMon/green.svg" alt="">&nbsp{{ item.systemName }}</div>
              </div>
            </div>
          </div>
        </a-tab-pane>
          <a-tab-pane tab="分项系统" key="3" v-if="showTreeLine||onlyShowTreeLine">
            <div style="margin-bottom: 12px;padding:0 16px">
              <slot name="left-top-line-inner"></slot>
            </div>
            <div style="height:60vh;overflow-y: auto;margin-top:5px;padding:0 16px">
              <a-alert type="info" :showIcon="true">
                <div slot="message">
                  当前选择：<span v-if="this.item.id">{{ this.item.systemName }}</span>
                  <a v-if="this.item.id" style="margin-left: 10px" @click="onClearLineSelected">取消选择</a>
                </div>
              </a-alert>
              <a-input-search v-model="lineText" @search="onSearchLine" style="width:100%;margin-top: 10px" placeholder="请输入分项系统名称"/>
              <a-col :md="10" :sm="24">
                <div class="tree-content">
                  <a-dropdown :trigger="[this.dropTrigger]" @visibleChange="dropStatus">
                <span style="user-select: none">
                  <a-tree key="linetree"    @select="onSelectLine" :selectedKeys="selectedLineKeys"
                          :checkedKeys="checkedLineKeys" :treeData="departLineTree" :checkStrictly="checkStrictly"
                          :expandedKeys="iExpandedLineKeys" :autoExpandParent="autoExpandParent" @expand="onExpandLine">
                    </a-tree>
                </span>
                  </a-dropdown>
                </div>
              </a-col>
<!--              <div :tabIndex="index" v-for="(item, index) in itemList"  style="position: relative;margin-top:5px">
                <input @click="handleDetail(item,index)" type="radio" class="faux" :value="item" :checked="iIndex==index"
                       name="inst" />
                <div class="inst-item">

                  <div v-if="item.status"><img src="~@/assets/eneMon/green.svg" alt="">&nbsp{{
                      item.systemName }}</div>
                  <div v-else><img style="filter: grayscale(100%)"
                                   src="~@/assets/eneMon/green.svg" alt="">&nbsp{{ item.systemName }}</div>
                </div>
              </div>-->
            </div>
          </a-tab-pane>
      </a-tabs>
      </a-card>
    </a-col>
    <a-col :md="19" :sm="24">
      <div>
        <slot name="right-content"></slot>
      </div>

    </a-col>
  </a-row>
</template>
<script>
import {
  queryUnitPartTreeList,
  searchUnitPartByKeywords
} from '@api/api'
import {getAction, httpAction} from '@api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { deleteTreeData } from '@/utils/util'
import Vue from 'vue'
import * as echarts from 'echarts'
// 表头

export default {
  name: 'DepartList',
  mixins: [JeecgListMixin],
  components: {
  },
  props: {
    fenqu: Number,
    cancheckable:Boolean,
    showLine:{
      type:Boolean,
      default:false
    },
    onlyShowLine:{
      type:Boolean,
      default:false
    },
    showTreeLine:{
      type:Boolean,
      default:false
    },
    onlyShowTreeLine:{
      type:Boolean,
      default:false
    }
  },

  data() {
    return {
      // line
      treeLineData:[],
      departLineTree:[],
      iExpandedLineKeys: [],
      allTreeLineKeys:[],
      selectedLineKeys: [],
      checkedLineKeys: [],
      lineText:'',
      tabVal:1,
      iIndex:-1,
      itemListB:[],
      itemList:[],
      item:{},
      type: this.fenqu==null?1:this.fenqu,
      iExpandedKeys: [],
      loading: false,
      autoExpandParent: true,
      currFlowId: '',
      currFlowName: '',
      disable: true,
      treeData: [],
      visible: false,
      departTree: [],
      rightClickSelectedKey: '',
      rightClickSelectedOrgCode: '',
      hiding: true,
      model: {},
      dropTrigger: '',
      depart: {},
      disableSubmit: false,
      checkedKeys: [],
      selectedKeys: [],
      autoIncr: 1,
      currSelected: { title: '' },
      allTreeKeys: [],
      checkStrictly: true,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      graphDatasource: {
        nodes: [],
        edges: []
      },
      orgCategoryDisabled: false,
      oldDirectorUserIds: ''
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },

  },

  methods: {
    changeTabs(val){
      this.tabVal=val
      if(val=='1'){
        this.loadData()
      }
      if(val=='2'){
        this.getLine()
      }
      if(val=='3'){
        this.loadTreeLine()
      }
    },

    handleDetail(item,index){
      this.iIndex=index
      this.item=item
      this.$emit('changeLine', item.id)
    },
    loadData() {
      this.refresh()
    },
    loadTreeLine(){
      const _that=this
      _that.treeLineData = []
      _that.departLineTree = []
    },
    loadTree() {
      var that = this
      that.treeData = []
      that.departTree = []

      queryUnitPartTreeList().then((res) => {
          if (res.success) {
            // 部门全选后，再添加部门，选中数量增多
            this.allTreeKeys = []
            that.currSelected.title = res.result[0].title
            for (let i = 0; i < res.result.length; i++) {
              let temp = res.result[i]
              that.treeData.push(temp)
              that.departTree.push(temp)
              that.setThisExpandedKeys(temp)
              that.getAllKeys(temp)
              // console.log(temp.id)
            }
            console.log("this.treeData",this.treeData)
            if(!this.cancheckable){
              this.selectedKeys = [this.treeData[0].key]
              this.$emit('init',this.selectedKeys[0])
            }
            this.loading = false
          }
        })
    },

    setThisExpandedLineKeys(node) {
      if (node.children && node.children.length > 0) {
        this.iExpandedLineKeys.push(node.key)
        for (let a = 0; a < node.children.length; a++) {
          this.iExpandedLineKeys.push(node.key)
          // this.setThisExpandedKeys(node.children[a])
        }
      }
    },
    setThisExpandedKeys(node) {
      if (node.children && node.children.length > 0) {
        this.iExpandedKeys.push(node.key)
        for (let a = 0; a < node.children.length; a++) {
          this.iExpandedKeys.push(node.key)
          // this.setThisExpandedKeys(node.children[a])
        }
      }
    },
    refresh() {
      this.loading = true
      this.loadTree()
    },
    onExpand(expandedKeys) {
      console.log('onExpand', expandedKeys)
      this.iExpandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onExpandLine(expandedKeys) {
      console.log('onExpand', expandedKeys)
      this.iExpandedLineKeys = expandedKeys
      this.autoExpandParent = false
    },
    backFlowList() {
      this.$router.back(-1)
    },
    // 右键点击下拉框改变事件
    dropStatus(visible) {
      if (visible == false) {
        this.dropTrigger = ''
      }
    },
    // 右键下拉关闭下拉框
    closeDrop() {
      this.dropTrigger = ''
    },
    addRootNode() {
      this.$refs.nodeModal.add(this.currFlowId, '')
    },
    onSearch(value) {
      let that = this
      if (value) {
        searchUnitPartByKeywords({ keyWord: value }).then((res) => {
          if (res.success) {
            that.departTree = []
            for (let i = 0; i < res.result.length; i++) {
              let temp = res.result[i]
              that.departTree.push(temp)
            }
          } else {
            that.$message.warning(res.message)
          }
        })
      } else {
        that.loadTree()
      }
    },
    onSearchLine(value) {
      this.lineText=value
      if (value||this.lineType) {
        this.itemList=this.itemListB.filter(e=>e.systemName.indexOf(value)!=-1&&e.type==this.lineType)
      } else {
        this.itemList=[...this.itemListB]
      }
    },
    filterTreeList(type){
      this.lineType=type
      this.onSearchLine(this.lineText)
    },
    nodeModalOk() {
      this.loadTree()
    },
    nodeModalClose() {
    },
    onCheck(checkedKeys, info) {
      console.log('onCheck', checkedKeys, info)
      this.hiding = false
      // ---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------
      if (this.checkStrictly) {
        this.checkedKeys = checkedKeys.checked
      } else {
        this.checkedKeys = checkedKeys
      }
      //传个type出去判断用能还是物理
      this.$emit('changeWorkshop', this.checkedKeys,this.type)


      // ---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------
    },

    onSelect(selectedKeys, e) {
      console.log('selected', selectedKeys, e)
      this.hiding = false
      let record = e.node.dataRef
      console.log('onSelect-record', record)
      this.currSelected = Object.assign({}, record)
      this.model = this.currSelected
      this.selectedKeys = [record.key]
      this.model.parentId = record.parentId
      this.setValuesToForm(record)
      this.oldDirectorUserIds = record.directorUserIds
      if(!this.cancheckable){
        this.$emit('changeWorkshop', this.selectedKeys[0],this.type)
      }

      // update-beign-author:taoyan date:20220316 for: VUEN-329【bug】为什么不是失去焦点的时候，触发手机号校验
      // update-end-author:taoyan date:20220316 for: VUEN-329【bug】为什么不是失去焦点的时候，触发手机号校验
    },
    onSelectLine(selectedKeys, e) {

      console.log('onSelectLine', selectedKeys, e)
      this.hiding = false
      let record = e.node.dataRef
      console.log('onSelect-record', record)
      if(record.disableCheckbox) return
      this.currSelected = Object.assign({}, record)
      this.model = this.currSelected
      this.selectedLineKeys = [record.key]
      this.model.parentId = record.parentId
      this.setValuesToForm(record)
      this.oldDirectorUserIds = record.directorUserIds
      if(!this.cancheckable){
        this.$emit('changeSubsystem', this.selectedLineKeys[0])
      }

      // update-beign-author:taoyan date:20220316 for: VUEN-329【bug】为什么不是失去焦点的时候，触发手机号校验
      // update-end-author:taoyan date:20220316 for: VUEN-329【bug】为什么不是失去焦点的时候，触发手机号校验
    },
    // 触发onSelect事件时,为部门树右侧的form表单赋值
    setValuesToForm(record) {
      if (record.orgCategory == '1') {
        this.orgCategoryDisabled = true
      } else {
        this.orgCategoryDisabled = false
      }
    },
    getCurrSelectedTitle() {
      return !this.currSelected.title ? '' : this.currSelected.title
    },
    onClearLineSelected(){
      this.iIndex=-1
      this.item={}
      this.$emit('changeLine', null)
    },
    onClearSelected() {
      this.hiding = true
      this.checkedKeys = []
      this.currSelected = {}
      this.selectedKeys = []
      this.$emit('changeWorkshop', this.checkedKeys,this.type)
    },
    handleNodeTypeChange(val) {
      this.currSelected.nodeType = val
    },
    notifyTriggerTypeChange(value) {
      this.currSelected.notifyTriggerType = value
    },
    receiptTriggerTypeChange(value) {
      this.currSelected.receiptTriggerType = value
    },

    submitCurrForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (!this.currSelected.id) {
            this.$message.warning('请点击选择要修改部门!')
            return
          }

          // update-begin---author:wangshuai ---date:20200308  for：[JTC-119]在部门管理菜单下设置部门负责人
          this.currSelected.oldDirectorUserIds = this.oldDirectorUserIds
          // update-end---author:wangshuai ---date:20200308  for：[JTC-119]在部门管理菜单下设置部门负责人

          httpAction(this.url.edit, this.currSelected, 'put').then((res) => {
            if (res.success) {
              this.$message.success('保存成功!')
              this.loadTree()
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },
    emptyCurrForm() {
      this.$refs.form.resetFields()
      this.model = {}
    },
    nodeSettingFormSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          console.log('Received values of form: ', this.model)
        }
      })
    },
    openSelect() {
      this.$refs.sysDirectiveModal.show()
    },
    selectDirectiveOk(record) {
      console.log('选中指令数据', record)
      this.nodeSettingForm.setFieldsValue({ directiveCode: record.directiveCode })
      this.currSelected.sysCode = record.sysCode
    },
    getFlowGraphData(node) {
      this.graphDatasource.nodes.push({
        id: node.id,
        text: node.flowNodeName
      })
      if (node.children.length > 0) {
        for (let a = 0; a < node.children.length; a++) {
          let temp = node.children[a]
          this.graphDatasource.edges.push({
            source: node.id,
            target: temp.id
          })
          this.getFlowGraphData(temp)
        }
      }
    },
    // ---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------
    expandAll () {
      this.iExpandedKeys = this.allTreeKeys
    },
    closeAll () {
      this.iExpandedKeys = []
    },
    checkALL () {
      this.checkStriccheckStrictlytly = false
      this.checkedKeys = this.allTreeKeys
    },
    cancelCheckALL () {
      // this.checkedKeys = this.defaultCheckedKeys
      this.checkedKeys = []
    },
    switchCheckStrictly (v) {
      if (v == 1) {
        this.checkStrictly = false
      } else if (v == 2) {
        this.checkStrictly = true
      }
    },
    initDictInfo(){
      let arr = this.dict.split(",")
      this.tableName = arr[0]
      this.text = arr[1]
      this.code = arr[2]
    },
    getAllLineKeys(node) {
      // console.log('node',node);
      this.allTreeLineKeys.push(node.key)
      if (node.children && node.children.length > 0) {
        for (let a = 0; a < node.children.length; a++) {
          this.getAllLineKeys(node.children[a])
        }
      }
    },
    getAllKeys(node) {
      // console.log('node',node);
      this.allTreeKeys.push(node.key)
      if (node.children && node.children.length > 0) {
        for (let a = 0; a < node.children.length; a++) {
          this.getAllKeys(node.children[a])
        }
      }
    },
    // ---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------

    // 产线
    getLine(){
      getAction("eneModeling/eneItemizeSystem/list",).then((res) => {
        this.itemList = res.result.records
        this.itemListB=res.result.records
        this.$emit('changeTabs')
      })
    }
  },
  created() {
    this.currFlowId = this.$route.params.id
    this.currFlowName = this.$route.params.name
    // this.loadTree()
  }

}
</script>
<style scoped>
.inst-item {
  padding: 4px 8px;
  height: 36px;
  font-size:14px;
}

.faux:hover+.inst-item {
  background-color: rgba(230, 247, 255, 0.3);
}

.inst-item>p:first-of-type {
  margin-bottom: 4px;
}

.faux:checked+.inst-item {
  background-color: rgba(230, 247, 255, 0.6);
}

.faux:not(:checked)+.inst-item {
  background-color: transparent;
}

.faux {
  display: block;
  position: absolute;
  height: 36px;
  opacity: 0;
  top: 0;
  left: 0;
  width: 100%;
  cursor: pointer;
}
</style>


